package com.army.stock.web;

import com.army.stock.domain.ArmyUser;
import com.army.stock.service.ArmyRoleService;
import com.army.stock.service.ArmyUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by zhangyong on 14/12/24.
 * 登录相关页面
 */
@Controller
public class LoginController {

    private static Logger logger = LoggerFactory.getLogger(LoginController.class);

    private static String LOGIN_PAGE = "login/login";

    @Autowired
    private ArmyUserService armyUserService;

    @Autowired
    private ArmyRoleService armyRoleService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginForGet() {
        logger.info("进入登录界面");
        return LOGIN_PAGE;
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String loginForPost(HttpServletRequest request, ModelMap modelMap) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        ArmyUser armyUser = armyUserService.checkLoginUser(username, password);
        logger.info("登陆用户名:" + armyUser);
        if (armyUser == null) {
            //前端提醒
            modelMap.put("error", "1");
            modelMap.put("username", username);
            return LOGIN_PAGE;
        }
        HttpSession session = request.getSession();
        session.setAttribute("username", username);
        String permits = armyRoleService.getPermitsByUserId(armyUser.getId());
        logger.info("username:{} ,permits:{}", username, permits);
        session.setAttribute("permits", permits);
        session.setAttribute("armyUser" ,armyUser);
        return "redirect:/";
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request, ModelMap modelMap) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.removeAttribute("username");
        }
        return "redirect:/login";
    }

}
